<template>
  <div class="mod-config">
    <basic-container>
      <div class="boxsty">
        <div class="flex justifyContentSpaceBetween">
          <div class="tabletext">规则管理（ 评议 ）</div>
          <div class="tablelink">
            <el-link icon="el-icon-plus" type="primary" v-if="permissions.ceping_cepinggzxxb_add" @click="gzxx_addOrUpdateHandle($event,null)" :underline="false">新增规则</el-link>
          </div>
        </div>
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()" class="form-inline">
          <el-form-item label="规则名称">
            <el-input v-model="dataForm.ruleName" style="width:300px" placeholder="请输入规则关键字进行检索"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" class="marginLeft" @click="zjOperation(1)">检索</el-button>
          </el-form-item>
        </el-form>
        <div class="avue-crud" style="height:60vh">
          <el-collapse v-model="activeName" v-for="(item,index) in dataList" :key="index" @change="querySubRuleHandler(item.id,index)" accordion>
            <el-collapse-item :name=index>
              <template slot="title">
                <div class="collapseBox">
                  <div class="flex alignItemsCenter">
                    <span class="numTip"> {{ index + 1 }}</span><span class="titleBox" style="margin-left:10px;"><span>规则名称：{{item.ruleName}}</span></span>
                  </div>
                  <div class="collapseSummary flex justifyContentSpaceBetween">
                    <div>
                      <div class="mb5"><span>创建时间：{{ stateFormat(item.createTime)}}</span><span class="marginLeft">模板类型：{{getsheetTypeDes(item.sheetType)}}</span></div>
                      <div class="mb5"><span>创建部门：{{item.createDeptName}}</span></div>
                      <!-- <div class="mb5"><span :class="Zt(item.hidden)">规则状态：{{item.hidden=='1'?"显示":"隐藏"}}</span><span class="marginLeft">表单类型：{{getsheetTypeDes(item.sheetType)}}</span></div> -->
                    </div>
                    <div>
                      <!-- <el-button v-if="permissions.ceping_cepinggzxxb_add && item.createDeptId === userInfo.deptId" type="primary" plain @click="updateRuleOrShowOrNoneHandler( $event,item.id,item.hidden)">
                        {{ item.hidden == '0' ? '显示' : '隐藏' }}
                      </el-button> -->
                      <el-button type="primary" plain v-if="permissions.ceping_cepinggzxxb_add" @click="copyRuleHandler($event,item.id)">复用</el-button>
                      <el-button type="primary" plain v-if="permissions.ceping_cepinggzxxb_add && item.createDeptId === userInfo.deptId" @click="gzmx_addOrUpdateHandle( $event,item.id,null,index)">新增题目</el-button>
                      <el-button type="primary" plain v-if="permissions.ceping_cepinggzxxb_edit && item.createDeptId === userInfo.deptId" @click="gzxx_addOrUpdateHandle($event,item.id)">编辑</el-button>
                      <el-button type="danger" plain v-if="permissions.ceping_cepinggzxxb_del && item.createDeptId === userInfo.deptId" @click="gzxx_deleteHandle($event,item.id)">删除</el-button>
                    </div>
                  </div>
                </div>
              </template>
              <div class="avue-crud">
                <el-table :data="item.subList" style="width: 100%;" stripe>
                  <el-table-column label="题目名称" prop="title" :show-overflow-tooltip='true'></el-table-column>
                  <el-table-column label="类型" :formatter="typeFormatter"  width="80" prop="itemType"></el-table-column>
                  <el-table-column label="排序号" prop="orderNo" width="70"></el-table-column>
                  <el-table-column label="操作" width="240" >
                    <template slot-scope="scope">
                      <el-button type="primary" plain v-if="permissions.ceping_cepinggzxxb_edit && item.createDeptId === userInfo.deptId" @click="gzmx_addOrUpdateHandle($event,scope.row.ruleId,scope.row.id,scope.row.pIndex)">编辑排序
                      </el-button>
                      <el-button type="danger" plain v-if="permissions.ceping_cepinggzxxb_del && item.createDeptId === userInfo.deptId" @click="gzmx_deleteHandle(scope.row.id,scope.row.pIndex,scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="avue-crud__pagination">
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      </div>
      <newform v-if="newformVisible" ref="newform"  @refreshDataList="getDataList"></newform>
      <dupform v-if="dupformVisible" ref="dupform"  @refreshDataList="getDataList"></dupform>
      <!-- 题目信息 弹窗, 新增 / 修改     -->
      <!-- <jxkhcpgzxxb v-if="gzxx_addOrUpdateVisible" ref="gzxx_addOrUpdate" @refreshDataList="zjOperation"></jxkhcpgzxxb> -->
      <!-- 规则明细 弹窗, 新增 / 修改 -->
      <subItem v-if="gzmx_addOrUpdateVisible" ref="gzmx_addOrUpdate" @getSubList="getSubList"></subItem>
      <!-- 规则明细 弹窗, 新增 / 修改 -->
      <!-- <cepinggzxxbfy v-if="cepinggzxxbfy" ref="cepinggzxxbfy" @refreshDataList="zjOperation"></cepinggzxxbfy> -->
    </basic-container>
  </div>
</template>

<script>
/**
 * 绩效考核_测评_评分规则管理列表
 * @author zgc
 * @date 2021-06-16 10:06:44
 * @date linh 2021-06-30 09:01:36 [删除增加判断逻辑]
 */
import {
  fetchList,
  delObj,
  updateRuleOrShowOrNone
} from '@/api/ceping/jxevalItemModel';
import {
  gzmxdelObj,
  querySubItemByPid
} from '@/api/ceping/jxevalruledetail';
import newform from './cepingNewForm';
import dupform from './cepingNewFormDup';
import subItem from './subItem';
// import cepinggzxxbfy from './evalOptDup';
import {
  mapGetters,mapState
} from 'vuex';
import {
  notify
} from 'element-ui';

export default {
  data() {
    return {
      dataForm: {
        title: '',
        hidden: '1'
      },
      options: [{
        value: '1',
        label: '显示'
      }, {
        value: '0',
        label: '隐藏'
      }],
      activeName: '',
      dataList: [
         
      ],
      mxUpdateOrAddIndex: '',
      mxUpdateOrAddPid: '',
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      gzmx_addOrUpdateVisible: false,
      gzxx_addOrUpdateVisible: false,
      newformVisible:false,
      dupformVisible:false,
      cepinggzxxbfy: false
    };
  },
  components: {
    // jxkhcpgzxxb,
    subItem,
    // cepinggzxxbfy
    newform,
    dupform
  },
  created() {
    this.getDataList();
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    ...mapGetters(['permissions'])
  },
  methods: {
     typeFormatter: function(row, column, cellValue) {
        var des = '';
        if(cellValue == '1') des = '单选'
        if(cellValue == '2') des = '多选'
        if(cellValue == '3') des = '问答'
        return des;
     },
        //显示问题类型描述
    getsheetTypeDes(sheetType){
        var des = '';
        if(sheetType === '3') des = '评议类模板'
        if(sheetType === '4') des = '推荐类模板'
        if(sheetType === '5') des = '调研类模板'
        return des;
    },
    //状态
    Zt(value) {
      return {
        yinCang: value === 0,
        green: value === 1,
      };
    },
    //主级修改增加返回
    zjOperation(page) {
 if (page){
   this.pageIndex = page
 }
      this.mxUpdateOrAddIndex = '';
      this.getDataList();
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      fetchList(Object.assign({
        current: this.pageIndex,
        size: this.pageSize,
      }, this.dataForm)).then(response => {
        this.dataList = response.data.data.records;
        this.totalPage = response.data.data.total;
        if (this.mxUpdateOrAddIndex === '') {
          this.activeName = '';
        } else {
          this.getSubList();
        }
      });
      this.dataListLoading = false;
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 新增 / 修改
    gzxx_addOrUpdateHandle(event, id) {
        event.stopPropagation();
        this.newformVisible = true;
        this.$nextTick(() => {
            this.$refs.newform.init(id);
        });
    
    },
    newformVisibleChildren(e){
        if(e){
         this.newformVisible = false;
        }
    },
    // 删除
    gzxx_deleteHandle(event, id) {
      event.stopPropagation();

      querySubItemByPid(id).then(res => {
        if (res.data.data.length > 0) {
          this.$notify.closeAll();
          this.$notify.error('存在下一级无法删除');
        } else {
          this.$confirm('是否确认删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            return delObj(id);
          }).then(data => {
            this.$notify.closeAll();
            this.$notify.success('删除成功');
            this.mxUpdateOrAddIndex = '';
            this.getDataList();
          });
        }
      })

    },
    //提交拷贝
    copyRuleHandler(e, id) {
      e.stopPropagation();
      this.dupformVisible = true;
      this.mxUpdateOrAddPid = id;
      this.$nextTick(() => {
        this.$refs.dupform.init(id);
      });
    },
    /**
     * 修改规则显示或隐藏
     */
    updateRuleOrShowOrNoneHandler(event, ruleId, hidden) {
      var data = {
        id: ruleId,
        hidden: hidden == '1' ? '0' : '1'
      };
    //   event.stopPropagation();
    //   querySubItemByPid(data).then(data => {
    //     this.$notify.closeAll();
    //     this.$notify.success('修改成功');
    //     this.mxUpdateOrAddIndex = '';
    //     this.getDataList();
    //   }).catch(() => {
    //     this.$notify.closeAll();
    //     this.$notify.error("修改失败");
    //   });
    },
    //  规则明细业务
    //规则明细 新增 / 修改
    gzmx_addOrUpdateHandle(event, ruleId, id, index) {
      event.stopPropagation();
      ////console.log("ruleId ", ruleId);
      // //console.log("id ",id);
      //  return false;
      var _this = this;
      _this.mxUpdateOrAddIndex = index;
      _this.mxUpdateOrAddPid = ruleId;
      _this.gzmx_addOrUpdateVisible = true;
      _this.$nextTick(() => {
        _this.$refs.gzmx_addOrUpdate.init(ruleId, id);
      });
    },
    //规则明细 删除
    gzmx_deleteHandle(id, praIndex, subIndex) {
      var _this = this;
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        _this.dataList[praIndex].subList.splice(subIndex, 1);
        _this.$forceUpdate();
        return gzmxdelObj(id);
      }).then(data => {
        this.$notify.closeAll();
        this.$notify.success('删除成功');
      });
    }, 
    //加载规则分值
    querySubRuleHandler(pid, index) {
      var _this = this;
      _this.mxUpdateOrAddIndex = index
    
      querySubItemByPid(pid).then(response => {
        var subList = response.data.data;
        for (var i = 0; i < subList.length; i++) {
          this.$set(subList[i], 'pIndex', index)
        }
        _this.$set(_this.dataList[index], 'subList', subList);
        //console.log(_this.dataList)
      }).catch(() => {
        this.$notify.error("规则分值查询失败");
      });
    },
    //新增更新后回调函数
    getSubList() {
      var _this = this;
      if(_this.mxUpdateOrAddPid == '') return false;
      querySubItemByPid(_this.mxUpdateOrAddPid).then(response => {
        var subList = response.data.data;
        for (var i = 0; i < subList.length; i++) {
          this.$set(subList[i], 'pIndex', _this.mxUpdateOrAddIndex)
        }
        _this.$set(_this.dataList[_this.mxUpdateOrAddIndex], 'subList', subList);
      }).catch(() => {
        this.$notify.error("规则分值查询失败");
      });
    },
    //格式化日期
    stateFormat(row) {
      return this.$moment(row.createTime).format("YYYY-MM-DD");
    },
  }
};

</script>
